<?php
namespace app\api\controller;

class InsuranceRefund extends Permission
{
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 1500;
        $map = [];
        $order = 'id DESC';

        if( isset($this->input_data['plate_number']) && $this->input_data['plate_number'] != '' ) $map['plate_number'] = $this->input_data['plate_number'];

        if( isset($this->input_data['status']) )
        {
            if( $this->input_data['status'] != 99999999 ) $map['a.status'] = $this->input_data['status'];
        }  

        if( isset($this->input_data['refund_to_driver']) ) $map['a.refund_to_driver'] = $this->input_data['refund_to_driver'];

        if( isset($this->input_data['insurance']) ) $map['b.insurance'] = ['LIKE','%'.$this->input_data['insurance'].'%'];

        if($this->post('area_id') > 0)
        {
            $map['area_id'] = $this->post('area_id');
        }
        else
        {
            $map['area_id'] = ['IN',$this->myAllAreaIds];
        }
        


        $total = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->where($map)->count();
        $rows = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->field('a.*,b.insurance,b.cate,b.insurance_salesman,b.refund_amount,b.refund_rebate,b.refund_pdf,b.refund_date,b.refund_to_driver_amount,b.refund_to_driver_images,c.plate_number,b.price,b.rebate_amount,b.raise_price')->order('id DESC')->order($order)->page($page,$limit)->where($map)->select();

        
        $list = [];
        foreach ($rows as $v) {
            $v['price'] = formatMoneyShow($v['price']);
            $v['raise_price'] = formatMoneyShow($v['raise_price']);
            $v['rebate_amount'] = formatMoneyShow($v['rebate_amount']);
            $v['refund_amount'] = formatMoneyShow($v['refund_amount']);
            $v['refund_rebate'] = formatMoneyShow($v['refund_rebate']);
            $v['refund_to_driver_amount'] = formatMoneyShow($v['refund_to_driver_amount']);
            $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
            $v['done_time'] = date('Y-m-d H:i',$v['done_time']);
            $v['refund_date'] = $v['refund_date'] == '0000-00-00' ? '' : $v['refund_date'];
            $v = $this->_getStatus($v);
            $list[] = $v;
        }
        
        $data = [
            'total' => $total,
            'list' => $list
        ];
        $this->resSuc($data);
    }

    private function _getStatus($v)
    {
        $text = [];
        $text[0] = '待处理';
        $text[20] = '已退保';
        $text[30] = '未通过';

        $type = [];
        $type[0] = 'info';
        $type[20] = 'success';
        $type[30] = 'danger';

        $v['statusText'] = $text[$v['status']];
        $v['statusType'] = $type[$v['status']];

        return $v;
    }

    public function del()
    {

        db('InsuranceRefund')->delete( $this->input_data['id']);
        
        $this->resSuc('ok');
    }

    public function update()
    {
        $map = [
            'id' => $this->input_data['id']
        ];
        $insurance = db('Insurance')->where($map)->find();
        if( $insurance['refund_time'] > 0 ) $this->resErr('此保单已退保');

        $map = [
            'insurance_id' => $this->input_data['id'],
            'status' => ['<',90], // 状态在90以下，表示正在退保，或者已经退保
        ];
        if( db('InsuranceRefund')->where($map)->find() ) $this->resErr('此保单正在退保中，无法重复提交');


        # 创建退保记录
        $data = [
            'insurance_id' => $this->input_data['id'],
            'refund_to_driver' => $this->input_data['refund_to_driver'] == '是' ? 1 : 0,
            'refund_reason' => $this->input_data['refund_to_driver'] == '否' ? '退保出统' :$this->input_data['refund_reason'],
            'refund_images' => $this->input_data['refund_images'],

            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $rId = db('InsuranceRefund')->insertGetId($data);

        # 如果满足条件（填了实际退保日期，传了退保批单，退保金额大于0），直接设置保单状态（更新退保数据就是）为已退保
        # 并且更新退保记录的状态
        if($this->input_data['refund_date'] != '' && $this->input_data['refund_pdf'] != '' && $this->input_data['refund_amount'] > 0)
        {
            # 直接设置保单状态（更新退保数据就是）为已退保
            $this->_updateInsuranceStatus($this->input_data['id']);

            # 并且更新退保记录的状态
            $sData = [
                'id' => $rId,
                'status' => 20,
                'done_user' => $this->user['realname'],
                'done_user_id' => $this->user['id'],
                'done_time' => time(),
            ];
            db('InsuranceRefund')->update($sData);

            # 创建收支
            $this->_createCost($insurance);
        }


        $this->resSuc('ok');
    }
    private function _createCost($insurance)
    {
        $data['io_type'] = '收入';
        $data['images'] = '';

        $data['relation_type'] = '退保';
        $data['relation_id'] = $insurance['id'];
        $data['status'] = 20; // 已完成

        $data['pay_user'] = $this->user['realname'];
        $data['pay_user_id'] = $this->user['id'];
        $data['pay_time'] = time();

        $data['create_user'] = $this->user['realname'];
        $data['create_user_id'] = $this->user['id'];
        $data['create_time'] = time();

        $data['pay_record_id'] = '';
        $data['vehicle_id'] = $insurance['vehicle_id'];
        $data['amount'] = formatMoneySave($this->input_data['refund_amount']);
        $data['cate'] = '退保';
        db('VehicleIncomeExpense')->insertGetId($data);

        $data['io_type'] = '支出';
        $data['amount'] = formatMoneySave($this->input_data['refund_rebate']);
        $data['cate'] = '退保险返点';
        db('VehicleIncomeExpense')->insertGetId($data);


        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$insurance['vehicle_id']]);
    }
    private function _updateInsuranceStatus($id)
    {
        # 查找相关保单
        $map = [
            'id' => $id
        ];
        $insurance = db('Insurance')->where($map)->find();

        $data = [
            'refund_amount' => formatMoneySave($this->input_data['refund_amount']),
            'refund_rebate' => formatMoneySave($this->input_data['refund_rebate']),
            'refund_date' => $this->input_data['refund_date'],
            'refund_pdf' => $this->input_data['refund_pdf'],

            'refund_time' => time(),
            'refund_user' => $this->user['realname'],
            'refund_user_id' => $this->user['id'],
        ];
        db('Insurance')->where($map)->update($data);

        # 更新车辆的保险到期时间
        $map = [
            'id' => $insurance['vehicle_id']
        ];

        $data = $insurance['cate'] == '交强险' ? ['insurance_date_c' => $this->input_data['refund_date']] : ['insurance_date_b' => $this->input_data['refund_date']];
        db('Vehicle')->where($map)->update($data);
    }

    # 填写退保信息
    // 完成退保，填完退保金额，返还返点，上传pdf，填写实际退保时间
    public function done()
    {
        $data = [
            'id' => $this->input_data['id'],
            'status' => 20,

            'done_user' => $this->user['realname'],
            'done_user_id' => $this->user['id'],
            'done_time' => time(),
        ];
        db('InsuranceRefund')->update($data);

        # 更新保单状态
        $this->_updateInsuranceStatus($this->input_data['insurance_id']);

        # 创建退保收支
        $insurance = db('Insurance')->where(['id'=>$this->input_data['insurance_id']])->find();
        $this->_createCost($insurance);


        $this->resSuc('ok');
    }

    public function getWatingPayToDriverList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 1500;
        $map = [
            'a.status' => 20, // 已从保险公司退保完成
            'refund_to_driver' => 1, // 需要退款给司机
            'refund_to_driver_time' => 0 // 还没退款的
        ];


        $total = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->where($map)->count();
        $rows = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->field('a.*,b.insurance,b.cate,b.insurance_salesman,b.refund_amount,b.refund_rebate,b.refund_pdf,b.refund_date,b.refund_to_driver_amount,b.refund_to_driver_images,c.plate_number')->order('id DESC')->order('id', 'desc')->page($page,$limit)->where($map)->select();

        
        $list = [];
        foreach ($rows as $v) {
            $v['refund_amount'] = formatMoneyShow($v['refund_amount']);
            $v['refund_rebate'] = formatMoneyShow($v['refund_rebate']);
            $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
            $v['done_time'] = date('Y-m-d H:i',$v['done_time']);
            $v['refund_date'] = $v['refund_date'] == '0000-00-00' ? '' : $v['refund_date'];
            $v = $this->_getStatus($v);
            $list[] = $v;
        }
        
        $data = [
            'total' => $total,
            'list' => $list
        ];
        $this->resSuc($data);
    }

    // 退款给司机
    public function payToDriver()
    {
        # 更新保单状态
        $data = [
            'refund_to_driver_amount' => formatMoneySave($this->input_data['refund_to_driver_amount']),
            'refund_to_driver_images' => $this->input_data['refund_to_driver_images'],
            'refund_to_driver_user' => $this->user['realname'],
            'refund_to_driver_user_id' => $this->user['id'],
            'refund_to_driver_time' => time(),
        ];
        $map = [
            'id' => $this->input_data['insurance_id']
        ];
        db('Insurance')->where($map)->update($data);
        $insurance = db('Insurance')->where($map)->find();
        $this->_createPayToDriverCost($insurance);
        $this->resSuc('ok');
    }

    private function _createPayToDriverCost($insurance)
    {
        $data['io_type'] = '支出';
        $data['images'] = '';
        $data['relation_type'] = '退保';
        $data['relation_id'] = $insurance['id'];
        $data['status'] = 20; // 已完成

        $data['pay_user'] = $this->user['realname'];
        $data['pay_user_id'] = $this->user['id'];
        $data['pay_time'] = time();

        $data['create_user'] = $this->user['realname'];
        $data['create_user_id'] = $this->user['id'];
        $data['create_time'] = time();

        $data['pay_record_id'] = '';
        $data['vehicle_id'] = $insurance['vehicle_id'];
        $data['amount'] = $insurance['refund_to_driver_amount'];
        $data['cate'] = '退保费给司机';
        db('VehicleIncomeExpense')->insertGetId($data);

        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$insurance['vehicle_id']]);
    }

    public function getById()
    {
        $map['id'] = $this->input_data['id'];
        $result = db('InsuranceRefund')->where($map)->find();
        $this->resSuc($result);
    }

}
